package org.flycloud.web.util;

import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;

public class UrlInfo {

	private String requestURL;

	private Map<String, List<String>> params = new HashMap<>();

	public String getRequestURL() {
		return requestURL;
	}

	public void setRequestURL(String requestURL) {
		this.requestURL = requestURL;
	}

	public Map<String, List<String>> getParams() {
		return params;
	}

	public void setParams(Map<String, List<String>> params) {
		this.params = params;
	}

	public static UrlInfo parse(HttpServletRequest request) {
		UrlInfo info = new UrlInfo();
		info.setRequestURL(request.getRequestURL().toString());

		for (String key : request.getParameterMap().keySet()) {
			for (String vs : request.getParameterMap().get(key)) {
				info.add(key, vs);
			}
		}

		return info;
	}

	public static UrlInfo parse(String url) {
		return null;
	}

	public void add(String key, String value) {
		List<String> ps = get(key);
		if (ps == null) {
			ps = new ArrayList<String>();
			put(key, ps);
		}
		ps.add(value);
	}

	public void put(String key, List<String> value) {
		params.put(key, value);
	}

	public List<String> get(String key) {
		return params.get(key);
	}

	public void del(String key) {
		params.remove(key);
	}

	@Override
	public String toString() {
		StringBuffer sb = new StringBuffer();
		sb.append(this.requestURL);
		sb.append("?");
		for (String key : params.keySet()) {
			for (String vs : params.get(key)) {
				sb.append(key);
				sb.append("=");
				sb.append(vs);
				sb.append("&");
			}
		}
		String url = sb.toString();
		return url.substring(0, url.length() - 1);
	}

	public static void main(String[] args) throws UnsupportedEncodingException {
		UrlInfo ui = new UrlInfo();
		ui.setRequestURL("http://localhost:8080");
		ui.add("a", "b1");
		ui.add("a", "b2");
		ui.add("c", "b1");
		ui.add("d", "b2");

		System.out.println(URLEncoder.encode(ui.toString(), "UTF8"));
		System.out.println(ui.toString());
	}
}
